<?php
require_once  'Kanedo/Acl/Exception.php';
require_once 'Kanedo/Session.php';
require_once 'Kanedo/Cookie.php';

class Login
{
	/**
	 * Datenbankverbindung
	 * @var Kanedo_Db $_db
	 */
	protected $_db = null;
	
	/**
	 * Benutzklasse
	 *
	 * @var User
	 */
	protected $_user = null;
	
	/**
	 * Cookieklasse
	 *
	 * @var Kanedo_Cookie
	 */
	protected $_cookie = null;
	/**
	 * Sessionklasse
	 *
	 * @var Kanedo_Session
	 */
	protected $_session = null;
	
	/**
	 * Konstruktor
	 * @param Kanedo_Db $db
	 */
	public function __construct(Kanedo_Db $db)
	{
		$this->_db = $db;
		if (!$this->_db->isConnected())
		{
			throw new Kanedo_Db_Exception("no_db_connection");
		}
		require_once 'User.php';
		$this->_user = new User($this->_db);
	}
	
	/**
	 * Funktion zu einloggen eines Benutzers
	 *
	 * @param string $name
	 * @param string $password
	 * @param bool $cookie
	 */
	public function login($name, $password,$cookie = false)
	{
		$user = $this->_user->getUserByColumn('nick', $name);
		$password = md5($password);
		if ($user['password'] == $password)
		{
			$session = new Kanedo_Session('user');
			$session->id = $user['id_user_user'];
			$session->user = $user;
			if ($cookie)
			{
				$cookie = new Kanedo_Cookie();
				$cookie->set('login', $user['hash'], 30);
			}
		}else {
			throw new Kanedo_Acl_Exception("invalid_login");
		}
		$this->_session = $session;
		$this->_cookie = $cookie;
	}
	
	/**
	 * Methode zum ausloggen des aktuellen Benutzers
	 *
	 */
	public function logout()
	{
		$session = new Kanedo_Session('user');
		$session->sessionDestroy();
		$cookie = new Kanedo_Cookie();
		$cookie->deleteCookie('login');
		$cookie->deleteCookie("PHPSESSID");
	}
	/**
	 * Erfragt de Status
	 *
	 * @return bool
	 */
	
	public function isLoggedIn()
	{
		$cookie = new Kanedo_Cookie();
		$session = new Kanedo_Session('user');
		if(($session->id) or ($cookie->login))
		{
			

			if (!$session->id)
			{
				$data = $this->_user->getUserByColumn('hash', $cookie->login);
				$session->user = $data;
				
			}
			return true;
		}else {
			return false;
		}
	}
	/**
	 * Gibt den aktuell angemeldeten Benutzer als User Objekt zurueck
	 *
	 * @return User
	 */
	public function getCurrentUser()
	{
		$this->_session = new Kanedo_Session('user');
		if ($this->isLoggedIn())
		{
			return $this->_session->user;
		}else {
			throw new Kanedo_Acl_Exception("no_user");
		}
	}
}
?>